package com.zeny.express.framework.file.service.impl;

import java.io.File;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.zeny.express.framework.file.FileStorageOperation;
import com.zeny.express.framework.file.dao.FileStorageEntityDao;
import com.zeny.express.framework.file.entity.FileStorageEntity;
import com.zeny.express.framework.file.service.FileStorageService;
import com.zeny.express.framework.shared.domain.Constants;
import com.zeny.express.framework.shared.util.UUIDUtils;

public class FileStorageServiceImpl implements FileStorageService {

	@Autowired
	private FileStorageEntityDao fileStorageEntityDao;

	@Autowired
	private FileStorageOperation fileStorageOperation;

	@Override
	public FileStorageEntity getFile(String fileId) {

		return fileStorageEntityDao.selectById(fileId);
	}

	@Override
	public String uploadFile(File file, String groupName) {
		
		return uploadFile(file, groupName, null, null);
	}

	@Override
	@Transactional("pbldb")
	public String uploadFile(File file, String groupName, String fileName, String contentType) {
		
		if (StringUtils.isEmpty(fileName)) {
			fileName = file.getName();
		}
		String serverFullName = fileStorageOperation.uploadFile(file,
				groupName, fileName);

		Date now = new Date();
		FileStorageEntity entity = new FileStorageEntity();

		entity.setId(UUIDUtils.getTimeUUID(now));
		entity.setActive(Constants.YES);
		entity.setCreateTime(now);
		entity.setModifyTime(now);
		entity.setGroupName(groupName);
		entity.setFileName(fileName);
		entity.setContentType(contentType);
		entity.setContentLength(file.length());
		entity.setServerFullName(serverFullName);

		fileStorageEntityDao.insert(entity);

		return entity.getId();
	}

	@Override
	@Transactional("pbldb")
	public void deleteFile(String fileId) {

		FileStorageEntity entity = fileStorageEntityDao.selectById(fileId);
		if (entity != null) {
			fileStorageEntityDao.delete(entity.getId());
		}

		fileStorageOperation.deleteFile(entity.getGroupName(),
				entity.getServerFullName());
	}

}
